package com.hnluchuan.bmjlearning.web.controller.admin;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.hnluchuan.bmjlearning.common.*;
import com.hnluchuan.bmjlearning.dto.*;
import com.hnluchuan.bmjlearning.common.CustomerStatus;
import com.hnluchuan.bmjlearning.model.AgentServicePackage;
import com.hnluchuan.bmjlearning.model.User;
import com.hnluchuan.bmjlearning.security.PasswordEncoder;
import com.hnluchuan.utils.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hnluchuan.bmjlearning.service.AgentService;

import com.hnluchuan.core.support.Page;
import com.hnluchuan.bmjlearning.web.controller.BaseController;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/admin/agent", produces="text/html;charset=UTF-8")
public class AdminAgentController extends BaseController {

	@Autowired
	private AgentService agentService;
	@Autowired
	private PasswordEncoder passwordEncoder;

	@RequestMapping(value = "/detail")
	public String detail(Map<String, Object> map, Long id) {
		UserDTO userDTO = getCurrentUserDTO();
		if(userDTO == null || userDTO.getType() != UserType.Manager.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}
		if (id != null) {
			AgentDTO dto = agentService.load(id);
			map.put("n", dto);

			List<AgentServicePackageDTO> agentServicePackageDTOList = agentServicePackageService.findByUserId(dto.getUser().getId());
			map.put("agentServicePackageList", agentServicePackageDTOList);
		}
		ServicePackageDTO servicePackageDTO = new ServicePackageDTO();
		servicePackageDTO.setStatus(ServicePackageStatus.Enabled.getValue());
		List<ServicePackageDTO> servicePackageDTOList = servicePackageService.find(servicePackageDTO, null);
		map.put("existedServicePackageList", servicePackageDTOList);
		return "admin/agent/agent_detail";
	}
	
	@ResponseBody
	@Transactional
	@RequestMapping(value = "/save")
	public String save(AgentDTO dto, HttpServletRequest request) throws Exception {
		if (dto.getMobile() != null) {
			if (dto.getMobile().length() != 11 ){
				throw new BizException("联系方式请输入11位有效手机号");
			}
		}
		UserDTO currentUserDTO = getCurrentUserDTO();
		if(currentUserDTO == null || currentUserDTO.getType() != UserType.Manager.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}

		String[] packageIdList = request.getParameterValues("servicePackageId");
		String[] packageCountList = request.getParameterValues("servicePackageCount");

		if(packageIdList != null && packageCountList != null) {
			if (packageCountList.length != packageIdList.length) {
				throw new BizException(ResultCode.SystemCrashed.getRemark());
			}
		}

		Map<Long, Integer> map = filterServicePackageData(packageIdList, packageCountList);


		if (dto.getId() == null) {
			UserDTO existedUser = userService.checkIfUsernameExist(dto.getMobile());
			if(existedUser != null){
				throw new BizException(ResultCode.MobileOccupy.getRemark());
			}
			UserDTO userDTO = new UserDTO();
			userDTO.setUsername(dto.getMobile());
			userDTO.setPassword(passwordEncoder.encodePassword(defaultPassword, defaultSalt));
			userDTO.setType(UserType.Agent.getValue());
			userDTO.setDeleted(DeleteStatus.NotDeleted.getValue());
			userDTO.setNickName(dto.getOrgName());
			Long userId = userService.create(userDTO);
			UserDTO newlyCreatedUser = userService.load(userId);

			userRoleService.deleteByUserId(userId);
			RoleDTO roleDTO = roleService.findByCode(UserType.Agent.getCode());
			userRoleService.addRole(userId, roleDTO.getId());

			dto.setStatus(AgentStatus.Enabled.getValue());
			dto.setCustomers(0);
			dto.setUser(newlyCreatedUser);
			Long agentId = agentService.create(dto);
			AgentDTO newlyCreatedAgent = agentService.load(agentId);
            if(!map.isEmpty()) {
				for (Map.Entry<Long, Integer> entry : map.entrySet()) {
					AgentServicePackageDTO agentServicePackageDTO = new AgentServicePackageDTO();
					agentServicePackageDTO.setUser(newlyCreatedUser);
					agentServicePackageDTO.setAgent(newlyCreatedAgent);
					agentServicePackageDTO.setCount(entry.getValue());
					ServicePackageDTO servicePackageDTO = servicePackageService.load(entry.getKey());
					agentServicePackageDTO.setServicePackage(servicePackageDTO);
					agentServicePackageDTO.setDeleted(DeleteStatus.NotDeleted.getValue());

					agentServicePackageService.create(agentServicePackageDTO);
				}
			}
		} else {

			AgentDTO old = agentService.load(dto.getId());
            User user = old.getUser();
            UserDTO existedUser = userService.checkIfUsernameExist(dto.getMobile());
            if(existedUser != null && !existedUser.getId().equals(user.getId())){
                throw new BizException(ResultCode.MobileOccupy.getRemark());
            }
			old.setMobile(dto.getMobile());
			old.setOrgName(dto.getOrgName());
			old.setManager(dto.getManager());
            agentService.updateAllFields(old);

            UserDTO userDTO = userService.load(old.getUser().getId());
            userDTO.setUsername(dto.getMobile());
            userDTO.setPassword(passwordEncoder.encodePassword(defaultPassword, defaultSalt));
            userDTO.setType(UserType.Agent.getValue());
            userDTO.setDeleted(DeleteStatus.NotDeleted.getValue());
            userDTO.setNickName(dto.getOrgName());
            userService.updateAllFields(userDTO);

            agentServicePackageService.deleteAllAgentServicePackageByUserId(userDTO.getId());
            if(!map.isEmpty()){
            	for(Map.Entry<Long, Integer> entry : map.entrySet()){
					AgentServicePackageDTO agentServicePackageDTO = new AgentServicePackageDTO();

					agentServicePackageDTO.setUser(userDTO);
					agentServicePackageDTO.setAgent(old);
					agentServicePackageDTO.setDeleted(DeleteStatus.NotDeleted.getValue());

            		Integer count = entry.getValue();
					agentServicePackageDTO.setCount(count);

					ServicePackageDTO servicePackageDTO = servicePackageService.load(entry.getKey());
					agentServicePackageDTO.setServicePackage(servicePackageDTO);

					agentServicePackageService.create(agentServicePackageDTO);
				}
			}
		}
		return ok();
	}

	private Map<Long, Integer> filterServicePackageData(String[] servicePackageIdList, String[] servicePackageCountList){
		Map<Long, Integer> map = new HashMap<>();
		if(servicePackageIdList != null && servicePackageCountList != null
				&& servicePackageIdList.length > 0 && servicePackageCountList.length > 0) {
			for (int i = 0; i < servicePackageCountList.length; i++) {
				if (StringUtils.isBlank(servicePackageCountList[i]) || StringUtils.isBlank(servicePackageIdList[i])) {
					continue;
				}
				Long id = Long.parseLong(servicePackageIdList[i]);
				Integer count = Integer.parseInt(servicePackageCountList[i]);
				if (map.get(id) != null) {
					map.put(id, map.get(id) + count);
				} else {
					map.put(id, count);
				}
			}
		}
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
	public String delete(Long id, Integer currentAgentStatus) throws IOException {
		UserDTO userDTO = getCurrentUserDTO();
		agentService.deleteOrActivateById(userDTO.getId(), id, currentAgentStatus);
		return ok();
	}
	
	@RequestMapping(value = "/list")
	public String list(AgentDTO dto, Boolean search, Map<String, Object> map, Page page) {
		UserDTO userDTO = getCurrentUserDTO();
		if(userDTO == null || userDTO.getType() != UserType.Manager.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}
		List<AgentDTO> dtos = agentService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		map.put("search", search);
		return "admin/agent/agent_list";
	}
	
	@RequestMapping(value = "/search")
	public String search(AgentDTO dto, Map<String, Object> map, Page page) {
		List<AgentDTO> dtos = agentService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/agent/agent_search";
	}

	@RequestMapping(value = "/deleteOrActivate")
    @ResponseBody
	public String deleteOrActivate(@RequestParam Long id, @RequestParam Integer status){
		UserDTO userDTO = getCurrentUserDTO();
		if(userDTO == null || userDTO.getType() != UserType.Manager.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}

		AgentDTO agentDTO = agentService.load(id);
		if(agentDTO == null || agentDTO.getUser() == null){
			throw new BizException(ResultCode.InvalidParameter.getRemark());
		}

		agentService.deleteOrActivateById(agentDTO.getUser().getId(), id, status);
		return ok();
	}

	@RequestMapping(value = "/checkDetail")
	public String checkDetail(Map<String, Object> map, CustomerServicePackageDTO customerServicePackageDTO, Page page, Long id) {
		UserDTO userDTO = getCurrentUserDTO();

		AgentDTO agent = agentService.load(id);
		if(agent == null){
			throw new BizException(ResultCode.InvalidParameter.getRemark());
		}
		map.put("agent", agent);
		Long agentUserId = agent.getUser().getId();

		List<AgentServicePackageDTO> agentServicePackageDTOList = agentServicePackageService.findAllIncludeHistoryByUserId(agentUserId);
		map.put("agentServicePackageList", agentServicePackageDTOList);

		customerServicePackageDTO.setUser(agent.getUser());
		customerServicePackageDTO.setId(null);
		customerServicePackageDTO.setDeleted(DeleteStatus.NotDeleted.getValue());
		List<CustomerServicePackageDTO> customerServicePackageDTOList = customerServicePackageService.find(customerServicePackageDTO, page);
		map.put("customerServicePackageList", customerServicePackageDTOList);

		map.put("query", customerServicePackageDTO);
		return "admin/agent/agent_checkDetail";
	}

    @RequestMapping(value = "/accountManageList")
    public String accountManageList(Map<String, Object> map, Page page) {
        return "admin/agent/agent_accountManageList";
    }

    @RequestMapping(value = "/accountManageDetail")
    public String accountManageDetail(Map<String, Object> map, Page page) {
        return "admin/agent/agent_accountManageDetail";
    }

	/**
	 * 代理商-医生管理页面
	 * @param map
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/agentCustomerList")
	public String agentCustomerList(Map<String, Object> map, Page page, CustomerDTO customerDTO) {
		/*UserDTO currentUser = getCurrentUserDTO();
		if(currentUser == null || currentUser.getType() != UserType.Agent.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}*/

		AgentDTO agentDTO = getCurrentAgentDTO();
		customerDTO.setAgent(agentDTO);
		List<CustomerDTO> customerDTOList = customerService.find(customerDTO, page);
		for(CustomerDTO c : customerDTOList){
			Date expiredDate = c.getExpireDate();
			Date now = new Date();

			Long restDays = 0L;
			if(expiredDate != null) {
				restDays = getDateDiff(now, expiredDate, TimeUnit.DAYS);
			}
			//restDays = restDays < 0 ? 0 : restDays;
			c.setRestDays(restDays.intValue());
		}
		map.put("list", customerDTOList);
		map.put("query", customerDTO);
		map.put("types", CustomerType.values());
		return "admin/agent/agent_customerManage_list";
	}

	/**
	 * 代理商-医生管理-新增/详情页面
	 * @param map
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/agentCustomerDetail")
	public String agentCustomerDetail(Map<String, Object> map, Page page, Long id) {
		UserDTO currentUser = getCurrentUserDTO();
		if(currentUser == null || currentUser.getType() != UserType.Agent.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}
		AgentDTO agentDTO = agentService.findByUserId(currentUser.getId());
		if(agentDTO == null){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}

		if(id != null){
			CustomerDTO customerDTO = customerService.load(id);
			map.put("customer", customerDTO);
			Date now = new Date();
			if (customerDTO.getExpireDate() != null) {
                Long days = getDateDiff(now, customerDTO.getExpireDate(), TimeUnit.DAYS);
                map.put("restDays", days);
            }
			List<CustomerServicePackageDTO> customerServicePackageDTOList = customerServicePackageService.findByCustomerId(id);
			for(CustomerServicePackageDTO c : customerServicePackageDTOList){
				Long servicePackageId = c.getServicePackage().getId();
				Long agentUserId = currentUser.getId();
				int validServicePackageCount =
						agentServicePackageService.getValidServicePackageCount(agentUserId, servicePackageId).intValue();

				c.setRemainCount(validServicePackageCount);
			}
			map.put("customerServicePackageList", customerServicePackageDTOList);
		}
        //List<ServicePackageDTO> existedServicePackageList = new ArrayList<>();
		List<ServicePackageDTO> servicePackageDTOList = servicePackageService.findByAgentId(agentDTO.getId());
		for(ServicePackageDTO s : servicePackageDTOList){
			int count = agentServicePackageService.getValidServicePackageCount(currentUser.getId(), s.getId()).intValue();
			s.setRemainCount(count);
			/*if (count > 0) {
                existedServicePackageList.add(s);
            }*/
		}
		map.put("id", id);
		map.put("existedServicePackageList", servicePackageDTOList);
		return "admin/agent/agent_customerManage_detail";
	}

	@ResponseBody
	@RequestMapping(value = "enableOrDisable", produces = "application/json;charset=utf-8")
	public String disableOrEnable(@RequestParam Long id, @RequestParam Integer status){
		UserDTO currentUser = getCurrentUserDTO();
		if(currentUser == null || currentUser.getType() != UserType.Agent.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}

		CustomerDTO customerDTO = customerService.load(id);
		if(customerDTO == null || customerDTO.getUser() == null){
			throw new BizException(ResultCode.InvalidParameter.getRemark());
		}

	    customerService.enableOrDisable(customerDTO.getUser().getId(), id, status);
		return ok();
	}

	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	@RequestMapping(value = "/agentCustomerDetail/save", method = RequestMethod.POST)
	public String saveAgentCustomerDetail(CustomerDTO dto, HttpServletRequest request){
	    if (dto.getMobile().length() != 11) {
	        throw new BizException(ResultCode.MobileFormatError.getRemark());
        }
		AgentDTO agentDTO = getCurrentAgentDTO();
		String[] packageIdList = request.getParameterValues("servicePackageId");
		String[] packageCountList = request.getParameterValues("servicePackageCount");
		if(packageIdList != null && packageCountList != null) {
			if (packageCountList.length != packageIdList.length) {
				throw new BizException(ResultCode.SystemCrashed.getRemark());
			}
		}

		Map<Long, Integer> map = filterServicePackageData(packageIdList, packageCountList);
		if (dto.getId() == null) {
			UserDTO existedUser = userService.checkIfUsernameExist(dto.getMobile());
			if(existedUser != null){
				throw new BizException(ResultCode.AccountOccupy.getRemark());
			}

			UserDTO userDTO = new UserDTO();
			userDTO.setUsername(dto.getMobile());
			userDTO.setPassword(passwordEncoder.encodePassword(defaultPassword, defaultSalt));
			userDTO.setType(UserType.Clinic.getValue());
			userDTO.setDeleted(DeleteStatus.NotDeleted.getValue());
			userDTO.setNickName(dto.getOrgName());
			Long userId = userService.create(userDTO);
			UserDTO newlyCreatedUser = userService.load(userId);

			userRoleService.deleteByUserId(userId);
			RoleDTO roleDTO = roleService.findByCode(UserType.Clinic.getCode());
			userRoleService.addRole(userId, roleDTO.getId());

			dto.setStatus(CustomerStatus.Enabled.getValue());
			dto.setUser(newlyCreatedUser);
			dto.setAgent(agentDTO);
			if(dto.getProvince() != null && dto.getProvince().getId() == null) {
				dto.setProvince(null);
			}
			if(dto.getCity() != null && dto.getCity().getId() == null){
				dto.setCity(null);
			}
			if(dto.getDistrict() != null && dto.getDistrict().getId() == null){
				dto.setDistrict(null);
			}
			Long customerId = customerService.create(dto);
			CustomerDTO newlyCreatedCustomer = customerService.load(customerId);
			Integer serviceDays = 0;
			if(!map.isEmpty()) {
				for (Map.Entry<Long, Integer> entry : map.entrySet()) {
					CustomerServicePackageDTO customerServicePackageDTO = new CustomerServicePackageDTO();
					customerServicePackageDTO.setUser(getCurrentUserDTO());
					customerServicePackageDTO.setCustomer(newlyCreatedCustomer);
					Integer count = entry.getValue();
					Long servicePackageId = entry.getKey();
					ServicePackageDTO servicePackageDTO = servicePackageService.load(servicePackageId);

					int validServicePackageCount =
							agentServicePackageService.getValidServicePackageCount(getCurrentUserDTO().getId(), servicePackageId).intValue();
					if(count > validServicePackageCount){
						throw new BizException(servicePackageDTO.getName() + ResultCode.LackOfServicePackage.getRemark());
					}

					customerServicePackageDTO.setCount(count);
					customerServicePackageDTO.setDeleted(DeleteStatus.NotDeleted.getValue());
					customerServicePackageDTO.setServicePackage(servicePackageDTO);

					serviceDays += count * servicePackageDTO.getExpireDays();

					customerServicePackageService.create(customerServicePackageDTO);

					AgentServicePackageDTO agentServicePackageDTO = agentServicePackageService.findByServicePackageIdAndAgentUserId(servicePackageId, getCurrentUserDTO().getId());
					agentServicePackageDTO.setCount(validServicePackageCount - count);
					agentServicePackageService.updateAllFields(agentServicePackageDTO);
				}
			}
            if (serviceDays != 0) {
                Date expireDate = addDays(newlyCreatedCustomer.getCreated(), serviceDays);
                newlyCreatedCustomer.setExpireDate(expireDate);
				Boolean isTestPackage = isTestPackage(packageIdList);
				if (isTestPackage) {
					newlyCreatedCustomer.setType(CustomerType.Test.getValue());
				} else {
					newlyCreatedCustomer.setType(CustomerType.OFFICIAL.getValue());
				}
				customerService.updateAllFields(newlyCreatedCustomer);
            } else {
				newlyCreatedCustomer.setType(CustomerType.INACTIVE.getValue());
				customerService.updateAllFields(newlyCreatedCustomer);
			}
			int customerCountBefore = agentDTO.getCustomers();
			agentDTO.setCustomers(customerCountBefore + 1);
			agentService.updateAllFields(agentDTO);
		} else {
			CustomerDTO old = customerService.load(dto.getId());
			User user = old.getUser();

			UserDTO existedUser = userService.checkIfUsernameExist(dto.getMobile());
			if(existedUser != null && !existedUser.getId().equals(user.getId())){
				throw new BizException(ResultCode.AccountOccupy.getRemark());
			}

			old.setIdCard(dto.getIdCard());
			old.setTitle(dto.getTitle());
			old.setSex(dto.getSex());
			if(dto.getProvince() != null && dto.getProvince().getId() == null) {
				old.setProvince(null);
			}else{
				old.setProvince(dto.getProvince());
			}
			if(dto.getCity() != null && dto.getCity().getId() == null){
				old.setCity(null);
			}else{
				old.setCity(dto.getCity());
			}
			if(dto.getDistrict() != null && dto.getDistrict().getId() == null){
				old.setDistrict(null);
			}else {
				old.setDistrict(dto.getDistrict());
			}
			old.setAddress(dto.getAddress());

			customerService.updateAllFields(old);
		}
		//更新
		JSONObject o = new JSONObject();
		AgentDTO currentAgentDTO = getCurrentAgentDTO();
		int customerCount = agentDTO.getCustomers();
		int newlyEnrolledCount = customerService.getTodayNewlyEnrolledCustomersCount(currentAgentDTO.getId());
		int remainPackageCount = agentServicePackageService.getValidServicePackageCount(getCurrentUserDTO().getId(), null).intValue();
		o.put("customerCount", customerCount);
		o.put("newlyEnrolledCount", newlyEnrolledCount);
		o.put("remainPackageCount", remainPackageCount);
		return ok(o);
	}

	/**
	 * 代理商-客户管理-续费页面
	 * @param map
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/agentCustomerRenew")
	public String agentCustomerRenew(Map<String, Object> map, Page page, Long id) {
		Long userId = getCurrentAgentDTO().getUser().getId();
		Long agentId = getCurrentAgentDTO().getId();
		CustomerDTO customerDTO = customerService.load(id);
        Date expireDate = customerDTO.getExpireDate();
		if (expireDate != null) {
            Date now = new Date();
            Long restDays = getDateDiff(now, expireDate, TimeUnit.DAYS);
            restDays = restDays < 0 ? 0 : restDays;
            customerDTO.setRestDays(restDays.intValue());
        }
		map.put("n", customerDTO);

		List<CustomerServicePackageDTO> customerServicePackageDTOList = customerServicePackageService.findByCustomerId(id);
		for(CustomerServicePackageDTO c : customerServicePackageDTOList){
			Long servicePackageId = c.getServicePackage().getId();
			int remainCount = agentServicePackageService.getValidServicePackageCount(userId, servicePackageId).intValue();

			c.setRemainCount(remainCount);
		}
		map.put("customerServicePackageList", customerServicePackageDTOList);
		ServicePackageDTO servicePackageDTO = new ServicePackageDTO();
		servicePackageDTO.setStatus(ServicePackageStatus.Enabled.getValue());
		//List<ServicePackageDTO> existedServicePackageList = servicePackageService.findOfficialByAgentId(agentId);
		List<ServicePackageDTO> existedServicePackageList = servicePackageService.findByAgentId(agentId);

		for(ServicePackageDTO s : existedServicePackageList){
			int remainCount = agentServicePackageService.getValidServicePackageCount(userId, s.getId()).intValue();
			s.setRemainCount(remainCount);
		}
		map.put("existedServicePackageList", existedServicePackageList);
		map.put("customerType", customerDTO.getType());
		return "admin/agent/agent_customerManage_renew";
	}

	@ResponseBody
	@RequestMapping(value = "/agentCustomerRenew/save")
	public String saveAgentCustomerRenew(HttpServletRequest request, Long id) {
		UserDTO currentUserDTO = getCurrentUserDTO();
		if(currentUserDTO == null || currentUserDTO.getType() != UserType.Agent.getValue()){
			throw new BizException(ResultCode.NotAuthorized.getRemark());
		}

		String[] packageIdList = request.getParameterValues("servicePackageId");
		String[] packageCountList = request.getParameterValues("servicePackageCount");

		if(packageIdList != null && packageCountList != null) {
			if (packageCountList.length != packageIdList.length) {
				throw new BizException(ResultCode.SystemCrashed.getRemark());
			}
		}
		Map<Long, Integer> map = filterServicePackageData(packageIdList, packageCountList);
		CustomerDTO old = customerService.load(id);

		Integer addedServiceDays = 0;
		if(!map.isEmpty()){
			for(Map.Entry<Long, Integer> entry : map.entrySet()){
				CustomerServicePackageDTO customerServicePackageDTO = new CustomerServicePackageDTO();

				customerServicePackageDTO.setUser(currentUserDTO);
				customerServicePackageDTO.setCustomer(old);
				customerServicePackageDTO.setDeleted(DeleteStatus.NotDeleted.getValue());

				Integer count = entry.getValue();
				Long servicePackageId = entry.getKey();
				int validServicePackageCount =
						agentServicePackageService.getValidServicePackageCount(currentUserDTO.getId(), servicePackageId).intValue();
				if(count > validServicePackageCount){
					throw new BizException(ResultCode.LackOfServicePackage.getRemark());
				}
				customerServicePackageDTO.setCount(count);

				ServicePackageDTO servicePackageDTO = servicePackageService.load(servicePackageId);
				customerServicePackageDTO.setServicePackage(servicePackageDTO);

				addedServiceDays += count * servicePackageDTO.getExpireDays();

				customerServicePackageService.create(customerServicePackageDTO);

				AgentServicePackageDTO agentServicePackageDTO = agentServicePackageService.findByServicePackageIdAndAgentUserId(servicePackageId, currentUserDTO.getId());
				agentServicePackageDTO.setCount(validServicePackageCount - count);
				agentServicePackageService.updateAllFields(agentServicePackageDTO);
			}
		}

		Date updatedExpiredDate = new Date();
		Boolean includeOfficial = servicePackageService.isIncludeOfficial(map);
		//填写了服务包并且不是第一次激活 正式用户续费 试用用户剩余的时长清除，从今天开始往后续费,并转为正式用户
		//续费操作只可选正式服务包。即续费一次就变成了正式账户
		if (old.getExpireDate() != null) {
			if ( old.getType().equals( (CustomerType.Test.getValue()) ) ){
				if (includeOfficial) {
					updatedExpiredDate = addDays(new Date(), addedServiceDays);
					old.setType(CustomerType.OFFICIAL.getValue());
				}else {
					if (old.getExpireDate().getTime()> updatedExpiredDate.getTime()) {
						updatedExpiredDate = addDays(old.getExpireDate(), addedServiceDays);
					} else {
						updatedExpiredDate = addDays(new Date(), addedServiceDays);
					}
				}
			} else {
				if (old.getExpireDate().getTime()> updatedExpiredDate.getTime()) {
					updatedExpiredDate = addDays(old.getExpireDate(), addedServiceDays);
				} else {
					updatedExpiredDate = addDays(new Date(), addedServiceDays);
				}
			}
            old.setExpireDate(updatedExpiredDate);
            customerService.updateAllFields(old);
        }else {
            //未激活状态 选择正式（试用）包 直接变成正式（试用）用户
            if (addedServiceDays != 0) {
				updatedExpiredDate = addDays(new Date(), addedServiceDays);
				if (includeOfficial) {
					old.setType(CustomerType.OFFICIAL.getValue());
				}else {
					old.setType(CustomerType.Test.getValue());
				}
                old.setExpireDate(updatedExpiredDate);
                customerService.updateAllFields(old);
            }
        }

		JSONObject o = new JSONObject();
		AgentDTO currentAgentDTO = getCurrentAgentDTO();
		int customerCount = currentAgentDTO.getCustomers();
		int newlyEnrolledCount = customerService.getTodayNewlyEnrolledCustomersCount(currentAgentDTO.getId());
		int remainPackageCount = agentServicePackageService.getValidServicePackageCount(getCurrentUserDTO().getId(), null).intValue();
		o.put("customerCount", customerCount);
		o.put("newlyEnrolledCount", newlyEnrolledCount);
		o.put("remainPackageCount", remainPackageCount);
		return ok(o);
	}

	/**
	 * 代理商-服务明细页面
	 * @param map
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/agentServiceList")
	public String agentServiceList(Map<String, Object> map, Page page, CustomerServicePackageDTO customerServicePackageDTO) {

		AgentDTO agentDTO = getCurrentAgentDTO();
		customerServicePackageDTO.setDeleted(DeleteStatus.NotDeleted.getValue());
		customerServicePackageDTO.setUser(getCurrentUserDTO());
		List<CustomerServicePackageDTO> customerServicePackageDTOList =
				customerServicePackageService.find(customerServicePackageDTO, page);
		List<ServicePackageDTO> existedServicePackageList =
				servicePackageService.findHistoryByAgentId(agentDTO.getId());
		map.put("list", customerServicePackageDTOList);
		map.put("n", customerServicePackageDTO);
		map.put("existedServicePackageList", existedServicePackageList);

		return "admin/agent/agent_serviceDetail_list";
	}

	//新增是，是否使用的试用包
	public Boolean isTestPackage (String[] packageIdList) {
		for (String packageId : packageIdList) {
			Long id = Long.parseLong(packageId);
			ServicePackageDTO dto = servicePackageService.load(id);
			if (dto.getType().equals(ServicePackageType.TEST.getValue())) {
				return true;
			}
		}
		return false;
	}

}
